<?php
class View_TreeStructure{
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $arrFolders
	 * @param unknown_type $essenceType
	 */
	public static function viewTreeStructure($arrFolders, $essenceType, $curId = NULL, $editFlag = false, $jsonFlag = false, $idFolder = NULL, $childrenFlag = false, $viewAllInEditMode = false, $closeOnClick = true, $login = '', $hide=false, $style=''){
		if (isset($arrFolders['arr_folder']))	$arrFolders = $arrFolders['arr_folder'];
		$class = !$childrenFlag ? 'class="filetree"' : '';
		echo '<ul ' . $class;
		echo ' style="' . ($hide ? 'display:none;' : '') . $style . '"';
		echo '>';
		//echo '<pre>';print_r($arrFolders);
		foreach ($arrFolders as $arrFolder) {
			if (TreeStructure::editCheck($essenceType) != 'programming_language')
				self::viewCurFolder($arrFolder, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, $childrenFlag, $viewAllInEditMode, $closeOnClick, $login);
			elseif (!$editFlag or ($editFlag and $viewAllInEditMode) or (($editFlag and $arrFolder[TreeStructure::editCheck($essenceType) . '_amount'] > 0 ) or ($editFlag and isset($arrFolder['children']))))
				self::viewCurFolder($arrFolder, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, $childrenFlag, $viewAllInEditMode, $closeOnClick, $login);
		}
		echo '</ul>';
	}

	public static function viewAllTreeStructure($arrFolders, $essenceType, $curId = NULL, $editFlag = false, $linearFlag = false, $idUser = NULL, $jsonFlag = false, $idFolder = NULL, $viewAllInEditMode = false, $closeOnClick = true, $login = '', $hide=true){
		if (isset($arrFolders['arr_folder']))
			$arrFolders = $arrFolders['arr_folder'];
		if ($editFlag)
			$essenceType .= '_edit';
			/*		echo '<pre>';
		print_r($arrFolders);
		echo '</pre>';*/

		$editFlag ? $attrEditFlag = "edit" : $attrEditFlag = '';
			if ($jsonFlag){

				$onClick1 = "setUserVariable(\'tree_structure_linear_flag\', 0); getTree(\'" . $essenceType . "\'); return false;";
				$onClick2 = "setUserVariable(\'tree_structure_linear_flag\', 1); showLinear(\'" . $essenceType . "\'); return false;";
				$readyFn = "\{treeStructure.linksToAddLinearControl(\'" . $essenceType . "\')\}";
			}
			else {
				$onClick1 = "setUserVariable('tree_structure_linear_flag', 0); getTree('" . $essenceType . "'); return false;";
				$onClick2 = "setUserVariable('tree_structure_linear_flag', 1); showLinear('" . $essenceType . "'); return false;";
				$readyFn = "{treeStructure.linksToAddLinearControl('" . $essenceType . "')}";
			}
		if (!$linearFlag){
			echo '<div id="' . $essenceType . '" class="treeview"><div id="structure" attrEditFlag="' . $attrEditFlag . '">';
				echo '<input type="hidden" id="structureType" value="tree"/>';
  		  echo '<ul class="name"><li class="active" id="liTreeStructure"><a href="/" id="aTreeStructure" onclick="' . $onClick1 . '"><span>Дерево категорий</span></a></li>';
  				if ($idUser) echo '<li id="liLinearStructure"><a href="/" id="aLinearStructure" onclick="' . $onClick2 . '"><span>Линейный список</span></a></li>';
  			echo '</ul>';
				if ($editFlag) {
					echo '<p style="font-weight: bold;">Режим выбора</p><script type="text/javascript"> $(document).ready(function()' . $readyFn . '); </script>';
				}
				echo '<div id="forAjaxLoadingStructure"></div><div id="treeStructure" >';
			View_TreeStructure::viewTreeStructure($arrFolders, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, false, $viewAllInEditMode, $closeOnClick, $login, $hide);
			echo '</div><div id="linearStructure"></div></div></div>';
		}
		else {
			echo '<div id="' . $essenceType . '"><div id="structure" attrEditFlag="' . $attrEditFlag . '">';
				echo '<input type="hidden" id="structureType" value="linear"/>';
		  echo '<ul class="name">';
				echo '<li id="liTreeStructure"><a href="/" id="aTreeStructure" onclick="' . $onClick1 . '"><span>Дерево категорий</span></a></li>';
				echo '<li class="active" id="liLinearStructure"><a href="/" id="aLinearStructure" onclick="' . $onClick2 . '"><span>Линейный список</span></a></li></ul>';
			if ($editFlag) {echo '<p style="font-weight: bold;">Режим выбора</p><script type="text/javascript"> $(document).ready(function()' . $readyFn . '); </script>';}
				echo '<div id="forAjaxLoadingStructure"></div><div id="linearStructure">';
				View_TreeStructure::viewLinearMenu($arrFolders, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, $closeOnClick, $login);
				echo '</div><div id="treeStructure"></div></div></div>';
		}
	}

	private static function viewCurFolder($arrFolder, $essenceType, $curId = NULL, $editFlag = false, $jsonFlag = false, $idFolder = NULL, $childrenFlag = false, $viewAllInEditMode = false, $closeOnClick = true, $login = ''){
/*echo '<pre> <b>DB:<br /></b>';
print_r($arrFolder);
echo '</pre>';*/
			$essenceTypeForEdit = $essenceType;
			if($editFlag)
				$essenceType = TreeStructure::editCheck($essenceType);
			$userRatingFlag = $essenceType == 'user_rating_tree' ? true : false;
			$id = $arrFolder['ID_folder'];
			if($jsonFlag){
				$editFlag ? $onClick = "curSelect(\'ID_" . $essenceTypeForEdit  . "_" . $id . "\', " . $id . ", \'tree\', \'" . $essenceTypeForEdit . "\', \'folder\', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
			}
			else {
				$editFlag ? $onClick = "curSelect('ID_" . $essenceTypeForEdit  . "_" . $id . "', " . $id . ", 'tree', '" . $essenceTypeForEdit . "', 'folder', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
			}
			$id == $idFolder ? $class = " treeStructureGreen " : $class = '';
			if ($editFlag) $class .= 'jsHref';
			$id == $idFolder ? $attrSelected = "attrSelected=\"selected\"" : $attrSelected = '';
			$counts = isset($arrFolder[$essenceType . '_amount']) ? ' (' . $arrFolder[$essenceType . '_amount'] . ')' : '';
			if ($essenceType == 'community'){
				$counts = NULL;
			}
			elseif ($userRatingFlag && isset($arrFolder['rating']))
				$counts = ' <strong>' . round($arrFolder['rating'], 2) . '</strong>';
			elseif ($essenceType == "programming_language")
				$counts = NULL;
			$url = self::getUrlFolderCurEssence($essenceType, $arrFolder, $login);


			$input = '';
			if ($id == $idFolder)
				$input = '<input class="selValueFolder" type="hidden" value="' . $id . '" name="selValueFolder"/>';
			if ($editFlag)
				echo $input;


		// вывод папки
		if ($editFlag)
			$url = '';
		$url = 'href="' . $url . '"';
		$closed = $arrFolder['ID_root_folder'] ? true : false; // сворачивать при старте все разделы
		!isset($arrFolder['description']) ? $arrFolder['description'] = '' : NULL;
		$liClass = ($userRatingFlag or $arrFolder['closed_at_start'] == 1 or $closed) ? 'class="closed"' : NULL;
		if($essenceType == 'userRating')
			$liClass = NULL;
		$essenceAttr = ' ';
		$noLinkAttr = ($essenceType == "question" or $essenceType == "solution" or $essenceType == "article" or $essenceType == "content_request");
		if (isset($arrFolder['array_' . $essenceType])){
			$arrEssenceInfo = self::getCurEssenceInfo($essenceType, $arrFolder);
			$essenceAttr = ' essenceAttr="' . $arrEssenceInfo['id'] . '" ';
		}
		elseif ($editFlag and !$noLinkAttr){
			$onClick = "return false;";
			$class = "noLink";
		}
		echo '<li attrClass="treeSelLi" id="ID_' . $essenceTypeForEdit  . '_' . $id . '" ' . $liClass . ' ><span attrIdFolder="' . $id . '" class="folder"' . $attrSelected . '><a attrCurId="' . $id . '"' . $essenceAttr . $url . ' class="' . $class . '" onclick="' . $onClick . '" attrClass="treeSelA" title="' . $arrFolder['description'] . '">' . $arrFolder['folder_name'] . '</a>' . $counts . (isset($arrFolder['place']) ? '<strong> (' . $arrFolder['place'] . '-й)</strong>' : '') . '</span>';

/*		if (isset($arrFolder['array_' . $essenceType])){
			echo '<ul>';
			foreach ($arrFolder['array_' . $essenceType] as $arrEssence){
				$counts = '';
				switch ($essenceType){
					case 'tutorial':{
						$url = W_ABSPATH . 'tutorial/' . $arrEssence['url_name'];
						$id = $arrEssence['ID_tutorial'];
					} break;
					case 'solution':{
						$url = W_ABSPATH . 'solutionList/' . $arrEssence['ID_category'] . '#solutions';
						$id = $arrEssence['ID_category'];
					}break;
					case 'question':{
						$url = W_ABSPATH . 'questions?folder=' . $arrEssence['ID_folder'] . '&pageNumber=1';
						$arrEssence['name'] = $arrEssence['folder_name'];
						$arrEssence['folder_name'] = NULL;
						$id = $arrEssence['ID_folder'];
						$counts = ' (' . $arrEssence['question_amount'] . ')';
					} break;
					default:{
						$url = W_ABSPATH . $essenceType . '/' . $arrEssence['ID_' . $essenceType];
						$id = $arrEssence['ID_' . $essenceType];
					}break;
				}
				!isset($arrEssence['description']) ? $arrEssence['description'] = '' : false;
				if($jsonFlag)
					$editFlag ? $onClick = "curSelect(\'ID_" . $essenceTypeForEdit  . "_" . $id . "\', " . $id . ", \'tree\', \'" . $essenceTypeForEdit . "\', \'file\', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
				else
					$editFlag ? $onClick = "curSelect('ID_" . $essenceTypeForEdit  . "_" . $id . "', " . $id . ", 'tree', '" . $essenceTypeForEdit . "', 'file', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
				$id == $curId ? $class = " treeStructureGreen file " : $class = '';
				if ($editFlag) $class .= 'jsHref';
				$id == $curId ? $attrSelected = "attrSelected=\"selected\"" : $attrSelected = '';
				echo '<li attrClass="treeSelLi" id="ID_' . $essenceTypeForEdit  . '_' . $id . '"><span class="file"' . $attrSelected . '><a attrCurId="' . $id . '" class ="' . $class . "\" onclick=\"" . $onClick . "\" attrClass=\"treeSelA\""; if (!$editFlag) echo 'href="' . $url . '"'; echo 'title="' . $arrEssence['description'] . '">' . $arrEssence['name'] . $counts . '</a></span>';
				$input = '';
				if ($id == $curId)
					$input = '<input class="selValue" type="hidden" value="' . $id . '" name="selValue"/>';
				if ($editFlag)
					echo $input;
				echo '</li>';
			}
			if (isset($arrFolder['children'])){
				View_TreeStructure::viewTreeStructure($arrFolder['children'], $essenceTypeForEdit, $curId, $editFlag, $jsonFlag, $idFolder, true, $viewAllInEditMode, $closeOnClick);
				echo '</ul>';
			}
			else {
				echo '</ul>';
			}
		}*/
		if (isset($arrFolder['children']))
			View_TreeStructure::viewTreeStructure($arrFolder['children'], $essenceTypeForEdit, $curId, $editFlag, $jsonFlag, $idFolder, true, $viewAllInEditMode, $closeOnClick, $login);
		echo '</li>';
	}

		/**
	 * Функция формирует категорию в тег option
	 *
	 * @param array $arrFolder - массив с именем и id категории
	 * @param int $idFolder - id папки, которую нужно выделить
	 * @param int $whitespace - кол-во пробелов перед ребёнком предыдущей категории
	 */
	private static function viewOptionForSelectFolder($arrStructure, $essenceType, $idStructure, $id, $whitespace, &$arrEssence){
		$selected = '';
		$space = '';
		if ($arrStructure['id_structure'] == $idStructure)
			$selected = 'selected';
		for ($i = 0; $i < $whitespace; $i++){
			$space .= '&nbsp;';
		}
		echo '<option ' . $selected . ' value="' . $arrStructure['id_structure'] . '"> ' . $space . $arrStructure['name'] . '</option>';
		//if (isset($arrStructure['array_' . $essenceType])){
			$options = '';
			$style = ' style="display:none"; ';
			$size = 1;
			foreach ($arrStructure['array_' . $essenceType] as $arrEssences){
				switch ($essenceType){
					case 'solution':
						$value = $arrEssences['ID_category']; break;
					case 'question':{
						$value = $arrEssence['ID_Structure'];
						$arrEssence['name'] = $arrEssence['Structure_name'];
						$arrEssence['Structure_name'] = NULL;
						} break;
					default:
						$value = $arrEssence['ID_' . $essenceType]; break;
				}
				$selected = '';
				if ($value == $id){
					$selected = 'selected';
					$style = '';
				}
				$size++;
				!isset($arrEssences['description']) ? $arrEssences['description'] = '' : false;
				$options .= '<option ' . $selected . ' value="' . $value . '" title="' . $arrEssences['description'] . '"> ' . $arrEssences['name'] . '</option>';
			}
			$arrEssence[] = '<select class="essenceSelect" attrIdStructure="' . $arrStructure['ID_Structure'] . '" name="essence" size="' . $size . '"' . $style . '>' . $options . '</select>';
		//}
	}
	/**
	 * Функция формирует категории языков в select со структурой
	 *
	 * @param array $arrFolder - отструктурированный массив с id и именем категории
	 * @param array $arrLanguage - массив со всеми языками
	 * @param int $idFolder - id папки, которую нужно выделить
	 * @param int $whitespace - кол-во пробелов перед ребёнком предыдущей категории
	 */
	private static function viewTreeFoldersForSelect($arrFolders, $essenceType, $idFolder = NULL, $id = NULL, $whitespace = NULL, &$arrEssence){
		foreach ($arrFolders as $arrFolder){
//			if ($arFolder['language_amount'] != 0) // убираем пустые папки
				self::viewOptionForSelectFolder($arrFolder, $essenceType, $idFolder, $id, $whitespace, &$arrEssence);
			if (isset($arrFolder['children']))
				self::viewTreeFoldersForSelect($arrFolder['children'], $essenceType, $idFolder, $id, $whitespace + 2, &$arrEssence);
		}
	}
	/**
	 * Функцию вывода на экран сформированной структуры категорий
	 *
	 * @param array $arrFolderLanguage - массив с древовидными папками и их количеством
	 * @param array $arrLangForCurFolder - массив с языками для конкретной папки, которую нужно выделить
	 */
	public static function viewTreeStructureForSelect($arrFolders, $essenceType, $idFolder = NULL, $id = NULL){
		$foldersCount = $arrFolders['folder_size'];
		$arrFolders = $arrFolders['arr_folder'];
		$selected = '';
		if (is_NULL($idFolder) && is_NULL($id))
			$selected = 'selected';
		echo '<select id="folder" name="folder" onchange="showCurSelection(this.form);"
		size="' . ($foldersCount + 2) . '">
		<option value="0" ' . $selected . '>Выберите папку</option>';
		$selected = '';
		$arrEssence = array();
		self::viewTreeFoldersForSelect($arrFolders, $essenceType, $idFolder, $id, 0, &$arrEssence);
/*		if (sizeof($arrLangForCurFolder) > 0){  //
			$options = $arrLangForCurFolder['options'];
			$size = $arrLangForCurFolder['size'] + 1;
			$style = '';
		}
		else {
			$size = 2;
			$options = '';
			$style = ' style="display:none"; ';
		}*/
		echo '</select>';
		foreach ($arrEssence as $curSelect){
			echo $curSelect;
		}
//		echo '</select><select id="language" name="lang" size="' . $size . '"' . $style . '>' . $options . '</select>';
	}
	/**
	 * Функция возвращает языки в тегах option для категории
	 *
	 * @param array $arrLang - массив с языками для данной папки
	 * @param int $idFolder - id категории
	 * @param int $selectedLangId - id языка, если передаётся, то папка с этим языком выделяется
	 * @return array
	 */
	public static function getLanguageForFolder($arrLang, $idFolder, $selectedLangId = NULL){
		$options = '';
		$selected = '';
		$size = sizeof($arrLang);
		foreach ($arrLang as $arrLanguage){
			if ($arrLanguage['ID_language'] == $selectedLangId)
				$selected = ' selected ';
			$options .= '<option class="folder_' .
			$idFolder . '" value="' . $arrLanguage['ID_language'] . '" ' .
			$selected . '>' .
			$arrLanguage['language'] . '</option>';
			$selected = '';
		}
		return array('options' => $options, 'size' => $size, 'ID_folder' => $idFolder);
	}

	public static function viewLinearMenu($arrFolders, $essenceType, $curId = NULL, $editFlag = false, $jsonFlag = false, $idFolder = NULL, $closeOnClick = true, $login = ''){
		if (isset($arrFolders['arr_folder']))
			$arrFolders = $arrFolders['arr_folder'];
		echo '<ul class="filetree">';
		View_TreeStructure::viewLinearStructure($arrFolders, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, false, $closeOnClick, $login);
		if (sizeof($arrFolders) == 0)
			echo '<p><b>Ни один раздел не добавлен в линейный список пользователя</b></p><br /><p>Чтобы добавить, нажмите на кнопку Сделать раздел любимым при выбранном разделе в древовидном списке</p>';
		echo '</ul>';
	}
	private static function viewLinearStructure($arrFolders, $essenceType, $curId = NULL, $editFlag = false, $jsonFlag = false, $idFolder = NULL, $viewAllInEditMode = false, $closeOnClick = true, $login = ''){
		foreach ($arrFolders as $arrFolder){
			if (TreeStructure::editCheck($essenceType) != 'programming_language')
				self::viewCurLinearFolder($arrFolder, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, $viewAllInEditMode, $closeOnClick, $login);
			elseif (!$editFlag or ($editFlag and $viewAllInEditMode) or ($editFlag and $arrFolder[TreeStructure::editCheck($essenceType) . '_amount'] > 0 ))
				self::viewCurLinearFolder($arrFolder, $essenceType, $curId, $editFlag, $jsonFlag, $idFolder, $viewAllInEditMode, $closeOnClick, $login);
		}
		$arrFoldersIds = array();
		foreach ($arrFolders as $arrFolder)
			$arrFoldersIds[] = $arrFolder['ID_folder'];
		$issetCurFolderInArray = in_array($idFolder, $arrFoldersIds);
/*		print_r($arrFoldersIds);
		if ($issetCurFolderInArray)
			echo '<b>TRUE</b>';
		else echo '<b>FALSE</b>';*/
		if (!$issetCurFolderInArray){
			echo '<li attrClass="treeSelLi" id="ID_' . $essenceType  . '_' . $idFolder . '" class="hiddenTreeStrLink"><span attrIdFolder="' . $idFolder . '" class="folder" attrSelected="selected"><a attrCurId="' . $idFolder . '" class="treeStructureGreen jsHref" attrClass="treeSelA"></a></span></li>';
		}

	}
	private static function viewCurLinearFolder($arrFolder, $essenceType, $curId = NULL, $editFlag = false, $jsonFlag = false, $idFolder = NULL, $viewAllInEditMode = false, $closeOnClick = true, $login = ''){
		$id = $arrFolder['ID_folder'];
			$essenceTypeForEdit = $essenceType;
			if($editFlag)
				$essenceType = TreeStructure::editCheck($essenceType);

		if($jsonFlag)
			$editFlag ? $onClick = "curSelect(\'ID_" . $essenceTypeForEdit  . "_" . $id . "\', " . $id . ", \'linear\', \'" . $essenceTypeForEdit . "\', \'folder\', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
		else
			$editFlag ? $onClick = "curSelect('ID_" . $essenceTypeForEdit  . "_" . $id . "', " . $id . ", 'linear', '" . $essenceTypeForEdit . "', 'folder', " . ($closeOnClick ? true : 0) . "); return false;" : $onClick = '';
		$id == $idFolder ? $class = " treeStructureGreen " : $class = '';
		if ($editFlag) $class .= 'jsHref';
		$id == $idFolder ? $attrSelected = "attrSelected=\"selected\"" : $attrSelected = "";
		$url = self::getUrlFolderCurEssence($essenceType, $arrFolder, $login);
		$essenceAttr = ' ';
		$noLinkAttr = ($essenceType == "question" or $essenceType == "solution" or $essenceType == "article" or $essenceType == "content_request");
		if (isset($arrFolder['array_' . $essenceType])){
			$arrEssenceInfo = self::getCurEssenceInfo($essenceType, $arrFolder);
			$essenceAttr = ' essenceAttr="' . $arrEssenceInfo['id'] . '" ';
		}
		elseif ($editFlag and !$noLinkAttr){
			$onClick = "return false;";
			$class = "noLink";
		}
		!isset($arrFolder['description']) ? $arrFolder['description'] = '' : false;
		$counts = isset($arrFolder[$essenceType . '_amount']) ? ' (' . $arrFolder[$essenceType . '_amount'] . ')' : '';
		echo '<li attrClass="treeSelLi" id="ID_' . $essenceTypeForEdit  . '_' . $id . '"><span attrIdFolder="' . $id . '" class="folder"' . $attrSelected . '><a title="' . $arrFolder['description'] . '" ' . $essenceAttr . 'attrCurId="' . $id . '" href="'; if (!$editFlag) echo $url; echo '" class="' . $class . '" onclick="' . $onClick . '" attrClass="treeSelA">' . $arrFolder['folder_name'] . $counts . '</a></span>';
		$input = '';
		if ($id == $idFolder)
			$input = '<input class="selValueFolder" type="hidden" value="' . $id . '" name="selValueFolder"/>';
		if ($editFlag)
			echo $input;

		//else echo '<li><span attrIdFolder="' . $arrFolder['ID_folder'] . '" class="folder">' . $arrFolder['folder_name'] . '</span>';
/*		if (isset($arrFolder['array_' . $essenceType])){
			echo '<ul>';
			foreach ($arrFolder['array_' . $essenceType] as $arrEssence){
				$counts = '';
				switch ($essenceType){
					case 'tutorial':{
						$url = W_ABSPATH . 'tutorial/' . $arrEssence['url_name'];
						$id = $arrEssence['ID_tutorial'];
					} break;
					case 'solution':{
						$url = W_ABSPATH . 'solutionList/' . $arrEssence['ID_category'] . '#solutions';
						$id = $arrEssence['ID_category'];
					}break;
					case 'question':{
						$url = W_ABSPATH . 'questions?folder=' . $arrEssence['ID_folder'] . '&pageNum=1';
						$arrEssence['name'] = $arrEssence['folder_name'];
						$arrEssence['folder_name'] = NULL;
						$id = $arrEssence['ID_folder'];
						$counts = ' (' . $arrEssence['question_amount'] . ')';
					} break;
					default:{
						$url = W_ABSPATH . $essenceType . '/' . $arrEssence['ID_' . $essenceType];
						$id = $arrEssence['ID_' . $essenceType];
					}break;
				}
				!isset($arrEssence['description']) ? $arrEssence['description'] = '' : false;
				if($jsonFlag)
					$editFlag ? $onClick = "curSelect(\'ID_" . $essenceTypeForEdit  . "_" . $id . "\', " . $id . ", \'linear\', \'" . $essenceTypeForEdit . "\', \'file\', " . ($closeOnClick ? true : 0) . "); return false;": $onClick="";
				else
					$editFlag ? $onClick = "curSelect('ID_" . $essenceTypeForEdit  . "_" . $id . "', " . $id . ", 'linear', '" . $essenceTypeForEdit . "', 'file', " . ($closeOnClick ? true : 0) . "); return false;": $onClick="";
				$id == $curId ? $class = " treeStructureGreen file " : $class = '';
				if ($editFlag) $class .= 'jsHref';
				$id == $curId ? $attrSelected = "attrSelected=\"selected\"" : $attrSelected = '';
				echo '<li attrClass="treeSelLi" id="ID_' . $essenceTypeForEdit  . '_' . $id . '"><span class="file"' . $attrSelected . '><a attrCurId="' . $id . '" class ="' . $class . "\" onclick=\"" . $onClick . "\" attrClass=\"treeSelA\""; if (!$editFlag) echo 'href="' . $url . '"'; echo 'title="' . $arrEssence['description'] . '">' . $arrEssence['name'] . $counts . '</a></span>';
				$input = '';
				if ($id == $curId)
					$input = '<input class="selValue" type="hidden" value="' . $id . '" name="selValue"/>';
				if ($editFlag)
					echo $input;
				echo '</li>';
			}
			echo '</ul>';
		}*/
	}

	/**
	 * отображение списка предложений разделов
	 *
	 * @param array $arrOfferTheme
	 * @param фккфн $arrVotingsControls
	 */
	public static function viewOfferFoler($arrOfferFolders){
		echo '<h2>Предлагаемые разделы</h2>
		<ul class="all_tem">';
		foreach ($arrOfferFolders as $arrOfferFolder){
//			$arrCurFolder = TreeStructure::getFolder($arrOfferFolder['ID_root_essence']);
// оптимизировать (folder.parents_id) и выводить путь !!!
			if ($arrOfferFolder['approved_status'] == 0){
				echo '<li><span title="' . $arrOfferFolder['name'] /*. ' Путь: ' .
				join('/', TreeStructure::getOfferedFoldersPath($arrCurFolder, $arrOfferFolder['name']))*/ . '">' .
				Service_String::cutString($arrOfferFolder['name'], 12) . '</span>
							<strong> Предложений: ' . Poll::calculateMark($arrOfferFolder['marks_minus'], $arrOfferFolder['marks_plus'], 1) . '</strong>';
				View_Poll::showMark($arrOfferFolder['ID_folder'], $arrOfferFolder['essence_type'], $arrOfferFolder['session_user_poll'], NULL, $arrOfferFolder['marks_minus'], $arrOfferFolder['marks_plus'], false, 1);
				echo '</li>';
			}
		}
				echo '</ul>';
	}
	/**
	 * получаем элемент li для списка заявок
	 *
	 * @param unknown_type $arrOffer
	 * @return unknown
	 */
	public static function getOfferLiElement($arrOfferFolder){
		$text = '<li><span>' . Service_String::cutString($arrOfferFolder['name'], 12) . '</span>
							<strong> Предложений: ' . Poll::calculateMark($arrOfferFolder['marks_minus'], $arrOfferFolder['marks_plus'], 1) . '</strong>';
		$text .= View_Poll::showMark($arrOfferFolder['ID_folder'], $arrOfferFolder['essence_type'], $arrOfferFolder['session_user_poll'], NULL, $arrOfferFolder['marks_minus'], $arrOfferFolder['marks_plus'], true, 1);
		$text .= '</li>';
		return $text;
	}

 /**
   * Выводим список предложенных пользователями разделов
   *
   * @param array $arrChapters
   */
  public static function showOfferedFoldersList(array $arrFolders) {
    echo '<form action="" method="POST" id="approveFoldersForm">
          <table cellcpacing="0" cellpadding="0" id="chapterOffersTable">
            <tr>
              <th>Название</th>
              <th>Путь</th>
              <th>Описание</th>
              <th>Первый пользователь</th>
              <th>Кол-во предложений</th>
              <th>Доп-но раздел является</th>
              <th>Выбрать</th>
            </tr>';
    $i = 0;
    foreach ($arrFolders as $arrFolder) {
  	  $arrCurFolder = TreeStructure::getFolder($arrFolder['ID_root_essence']); //Получаем информацию о родительском разделе для предложенного раздела
      echo '<tr id="id_offer_' . $arrFolder['ID_offer'] . '">
              <td>' . $arrFolder['name'] . '</td>
              <td>' . join('/', TreeStructure::getOfferedFoldersPath($arrCurFolder, $arrFolder['name'])) . '</td>
              <td class="desc" ondblclick="treeStructure.showEditForm(this, ' . $arrFolder['ID_offer'] . ')"><p>' . $arrFolder['description'] . '</p></td>
              <td>' . $arrFolder['login'] . '</td>
              <td>' . $arrFolder['amount'] . '</td>
              <td class="id_offer_' . $arrFolder['ID_offer'] . '">
              	<input type="checkbox" id="idEssence_7" name="tutorial_checkbox[' . $i . ']" class="id_offer_' . $arrFolder['ID_offer'] . '" onChange="treeStructure.approveFoldersTableControl(this);"><label> Самоучителем</label><br />
              	<div id="idEssence_7" style="display:none" >
              		<label>Название самоучителя для ссылок<br /></label>
              		<input type="text" name="tutorialNameForLink[' . $i . ']">
              	</div>
              	<input type="checkbox" id="idEssence_15" name="language_checkbox[' . $i . ']" class="id_offer_' . $arrFolder['ID_offer'] . '" onChange="treeStructure.approveFoldersTableControl(this);"><label> Языком программирования</label><br />
              	<div id="idEssence_15" style="display:none">
              		<label>Название файла для Geshi подсветки</label><br />
              		<input type="text" name="fileNameForLanguage[' . $i . ']">
              	</div>
              	<br />
              </td>
              <td><input type="checkbox" name="approved[' . $i . ']" value="' . $arrFolder['ID_offer'] . '"></td>
            </tr>';
      $i++;
    }
    echo '</table>
          <div class="collectionAction">
            <a href="#" onClick="return false;" title="" id="selectAll">Выделить все</a>, <a href="#" onClick="return false;" title="" id="selectNone">Снять выделение</a>
          </div>
          <input type="submit" name="actionApproveOfferedFolders" value="Утвердить" />
          <input type="submit" name="actionDeleteOfferedFolders" value="Удалить" />
          </form>';
  }

  /**
   * метод для вывода хлебных крошек
   */
  public static function viewBreadcrumbs($arrUrls, $srike = false, $textAfter = NULL){
  	$sizeof = sizeof($arrUrls);
  	$objSession = User_Session::instance();
  	$idUser = $objSession->getUserId();
  	if (!isset($arrUrls[1])){
	  	switch ($arrUrls[0]['name']){
	  		case 'Статьи':
	  			if ($idUser) $rssLinkLike = W_ABSPATH . 'articlesFoldersRSS/' . $idUser;
	  			$rssLinkMain = "http://feeds.feedburner.com/bitbybit/articlesRSS?format=xml";
	  			break;
	  		case 'Самоучитель':
	  			if ($idUser) $rssLinkLike = W_ABSPATH . 'tutorialsFoldersRSS/' . $idUser;
	  			$rssLinkMain = "http://feeds.feedburner.com/bitbybit/lessonsRSS?format=xml";
	  			break;
	  		case 'Вопросы и ответы':
	  			if ($idUser) $rssLinkLike = W_ABSPATH . 'questionsFoldersRSS/' . $idUser;
	  			$rssLinkMain = "http://feeds.feedburner.com/bitbybit/questionsRSS?format=xml";
	  			break;
	  		case 'Готовые решения':
	  			if ($idUser) $rssLinkLike = W_ABSPATH . 'solutionsFoldersRSS/' . $idUser;
	  			$rssLinkMain = "http://feeds.feedburner.com/BitByBit/SolutionsRSS?format=xml";
	  			break;
	  	}
  	}
  	
  	if (!empty($textAfter))
  	  echo '<div style="height: 8px;">&nbsp;</div>';
  	else
  	  echo '<br />';
  	echo '<div class="item">
  			<ul class="nav_tags">';
  	for($i = 0; $i < $sizeof; $i++){
  		if (!isset($arrUrls[$i]['show']) || (isset($arrUrls[$i]['show']) && $arrUrls[$i]['show'])){
	  		if ($i == $sizeof - 1 && !(isset($arrUrls[$i]['noLast']) && $arrUrls[$i]['noLast'])) {
	  			echo '<li class="last"><span'; if (isset($arrUrls[$i]['class'])) echo ' class="'.$arrUrls[$i]['class'].'"'; if(isset($arrUrls[$i]['style'])) echo ' style="' . $arrUrls[$i]['style'] . '"'; echo '>' . $arrUrls[$i]['name'] . '</span></li>'; // последний элемент
	  		}
	  		else {
	  			echo '<li '; if(isset($arrUrls[$i]['noLast']) && $arrUrls[$i]['noLast']) echo 'style="background: transparent none repeat scroll 0 0;"';  echo '><a href="' . $arrUrls[$i]['url'] . '"'; if (isset($arrUrls[$i]['class'])) echo ' class="'.$arrUrls[$i]['class'].'"'; if(isset($arrUrls[$i]['style'])) echo ' style="' . $arrUrls[$i]['style'] . '"'; echo '>' . $arrUrls[$i]['name'] . '</a></li>';
	  		}
  		}
  	}
  	if (!empty($textAfter)) echo '<li class="last">' . $textAfter . '</li>';
  	if (isset($rssLinkMain)) echo '<a class="rss" target="_blank" href="' . $rssLinkMain . '"><img id="rss_icon" src="' . W_IMAGES . 'icons/rss.png" title="Rss: ' . $arrUrls[0]['name'] . '"/></a>';
  	if (isset($rssLinkLike)) echo '<a class="rss_like" target="_blank" href="' . $rssLinkLike . '"><img id="rss_like_icon" src="' . W_IMAGES . 'icons/rss_like.png" title="Rss: ' . $arrUrls[0]['name'] . ' избранных разделов дерева"/></a>';
  	echo '</ul>
  			</div>';
  }
  
  //генерирует заголовок в title на основе breadCrumbs
  public static function makeHeaderByBreadCrumbs ($arrUrls) {
    $sizeof = sizeof($arrUrls);
    $header = '';
    for($i = 0; $i < $sizeof; $i++){
      $header = $arrUrls[$i]['name'] . $header;
      if ($i != $sizeof - 1) {
        $header = ' « ' . $header;
      }
    }
    return $header;
  }

  public static function viewFolderSelectLinks($idFolder, $folderName, $essenceType, $curId = NULL, $curName = '', $ajaxFlag = false, $showCur = true, $closeOnClick = true, $isToPersonalBlog = false){
  	if (!$idFolder && is_NULL($idFolder) || $idFolder == 'NULL')
  		$text = '<b>раздел не выбран (выбрать)</b>';
  	else $text = 'Выбран раздел ' . $folderName . ' (сменить)';
  	$curId = intval($curId);
  	$pText = '';
  	if (is_int($curId) and $curId != 0){
	  	switch ($essenceType){
	  		case 'tutorial': {/*$pText = 'выбран самоучитель ' . $curName;*/ $text = 'выбран самоучитель ' . $folderName . ' (сменить)'; break;}
	  		case 'programming_language': {/*$pText = 'выбран язык программирования ' . $curName;*/ $text = 'выбран язык программирования ' . $folderName . ' (сменить)'; break;}
	  		case 'solution': $pText = '';break;
	  		default: $pText = 'выбрана сущность ' . $curName; break;
	  	}
  	}
  	elseif ($showCur and (!is_int($curId) or $curId == 0))
	  	switch ($essenceType){
	  		case 'tutorial': $pText = '<b>Самоучитель не выбран</b>';break;
	  		case 'programming_language': $pText = '<b>Язык программирования не выбран</b>';break;
	  		case 'solution': $pText = '';break;
	  		default: '<b>Сущность не выбрана</b>'; break;
	  	}
	  else
  		$pText = '';
  	if (!$ajaxFlag)
  		echo '<div id="selectFolderLinkDiv"' . ($isToPersonalBlog ? ' style="display:none;"' : '') . '>';
  	echo '<a class="jsHref thickbox" onClick="return false;" title="Выбор раздела" href="' . W_ABSPATH . 'content/pages/treeStructure/treeForSelect.php?idFolder=' . ($idFolder ? $idFolder : 'NULL') . '&essenceType=' . $essenceType . '&curId=' . ($curId ? $curId : 'NULL') . '&closeOnClick=' . ($closeOnClick ? true : 0) . '" id="selectFolderLink">' . $text . '</a>
  				<p style="margin-top:1px;">' . $pText . '</p>
  				<div id="treeForSelectFolder" openTree="no" attrIdFolder="'; if ($idFolder) echo $idFolder; else echo 'NULL'; echo '" attrCurId="'; if ($curId) echo $curId; else echo 'NULL'; echo '"></div>';
/*  	if (!$idFolder)
  		echo '<script type="text/javascript">
  						$(document).ready(function(){
  							$("a#selectFolderLink").click();
  						});
  					</script>';*/
  	if (!$ajaxFlag)
  		echo '</div>';
  }


	/**
	 * url для ссылки на раздел сущности
	 *
	 * @param string $essenceType
	 */
	private static function getUrlFolderCurEssence($essenceType, $arrFolder, $login = ''){
		if (isset($arrFolder['array_' . $essenceType])){
			$arrEssenceInfo = self::getCurEssenceInfo($essenceType, $arrFolder);
			return $arrEssenceInfo['url'];
		}
		switch ($essenceType){
			case 'tutorial': return W_ABSPATH . 'tutorials?idFolder=' . $arrFolder['ID_folder'] . '&pageNum=1';
			case 'question': return W_ABSPATH . 'questions?folder=' . $arrFolder['ID_folder'] . '&pageNum=1';
			case 'content_request': return W_ABSPATH . 'crequest/?folder=' . $arrFolder['ID_folder'] . '&pageNum=1';
			case 'community': return W_ABSPATH . 'community/' . $arrFolder['ID_folder'] . '/1/';
			case 'article': return W_ABSPATH . 'articles?idFolder=' . $arrFolder['ID_folder'];
			case 'solution': return W_ABSPATH . 'solutions?idFolder=' . $arrFolder['ID_folder'] . '&pageNum=1';
			case 'user_rating_tree': return W_ABSPATH . 'users/?idFolder=' . $arrFolder['ID_folder'];
			default: return W_ABSPATH . 'structure/' . $essenceType . '/' . $arrFolder['ID_folder'];
		}
	}

	private static function getCurEssenceInfo($essenceType, $arrFolder){
		switch ($essenceType){
			case 'tutorial':{
				$arrFolder['array_' . $essenceType][0]['url'] = W_ABSPATH . 'tutorial/' . $arrFolder['array_' . $essenceType][0]['url_name'];
				$arrFolder['array_' . $essenceType][0]['id'] = $arrFolder['array_' . $essenceType][0]['ID_tutorial'];
			} break;
			case 'solution':{
				$arrFolder['array_' . $essenceType][0]['url'] = W_ABSPATH . 'solutionList/' . $arrFolder['array_' . $essenceType][0]['ID_category'] . '#solutions';
				$arrFolder['array_' . $essenceType][0]['id'] = $arrFolder['array_' . $essenceType][0]['ID_category'];
			}break;
			case 'question':{
				$arrFolder['array_' . $essenceType][0]['url'] = W_ABSPATH . 'questions?folder=' . $arrFolder['array_' . $essenceType][0]['ID_folder'] . '&pageNumber=1';
				$arrFolder['array_' . $essenceType][0]['name'] = $arrFolder['array_' . $essenceType][0]['folder_name'];
				$arrFolder['array_' . $essenceType][0]['folder_name'] = NULL;
				$arrFolder['array_' . $essenceType][0]['id'] = $arrFolder['array_' . $essenceType][0]['ID_folder'];
				$arrFolder['array_' . $essenceType][0]['counts'] = ' (' . $arrFolder['array_' . $essenceType][0]['question_amount'] . ')';
			} break;
			default:{
				$arrFolder['array_' . $essenceType][0]['url'] = W_ABSPATH . $essenceType . '/' . $arrFolder['array_' . $essenceType][0]['ID_' . $essenceType];
				$arrFolder['array_' . $essenceType][0]['id'] = $arrFolder['array_' . $essenceType][0]['ID_' . $essenceType];
			}break;
		}
		return $arrFolder['array_' . $essenceType][0];
	}

}
?>